//
//  ViewController.swift
//  SAMKeychainDemo
//
//  Created by Subo on 2017/6/30.
//  Copyright © 2017年 Followme. All rights reserved.
//

import Cocoa
import SAMKeychain

class ViewController: NSViewController {
    @IBOutlet weak var accountTextFeild: NSTextField!
    @IBOutlet weak var passwordTextFeild: NSTextField!
    
    let serviceName = "Service"

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


    @IBAction func savePassword(_ sender: NSButton) {
        let account = accountTextFeild.stringValue
        let password = passwordTextFeild.stringValue
        if account.isEmpty {
            showAlert(with: "请输入账户名")
            return
        }
        
        if password.isEmpty {
            showAlert(with: "请输入密码")
            return
        }
        
        if SAMKeychain.setPassword(password, forService: serviceName, account: account) {
            showAlert(with: "保存成功")
        }else {
            showAlert(with: "保存失败")
        }
    }
    
    @IBAction func getPassword(_ sender: NSButton) {
        let account = accountTextFeild.stringValue
        if account.isEmpty {
            showAlert(with: "请输入要查询的账户名")
            return
        }
        
        //这里会需要用户授权
        if let password = SAMKeychain.password(forService: serviceName, account: account) {
            passwordTextFeild.stringValue = password
            showAlert(with: "账户：\(account) 对应的密码为\(password)")
        }else {
            showAlert(with: "未找到对应密码或者用户没有授权")
        }
    }
    
    private func showAlert(with message: String) {
        let alert = NSAlert()
        alert.messageText = message
        alert.runModal()
    }
}

